package com.meiyou.controller;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.meiyou.pojo.MeiyouEvaluate;
import com.meiyou.pojo.MeiyouPtjls;
import com.meiyou.pojo.MeiyouXtinform;
import com.meiyou.pojo.MeiyouYhask;
import com.meiyou.pojo.MeiyouYuehui;
import com.meiyou.pojo.YuehuiDetails;
import com.meiyou.pojo.vo.YuehuiVo;
import com.meiyou.service.AppSettingService;
import com.meiyou.service.EvaContentService;
import com.meiyou.service.PtjlsService;
import com.meiyou.service.UserService;
import com.meiyou.service.XtinformService;
import com.meiyou.service.YueHuiService;
import com.meiyou.utils.Context;
import com.meiyou.utils.Msg;
import com.meiyou.utils.PagesMap;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@Api(value = "美游app控制器", tags = { "所有api接口" })
public class YueHuiController {
	@Resource
	private YueHuiService yueHuiServiceImpl;
	@Resource
	private AppSettingService appsetting;
	@Resource
	private PtjlsService ptjlsServiceImpl;
	@Resource
	private UserService userServiceImpl;
	@Resource
	private XtinformService xtinformServiceImpl;
	@Resource
	private EvaContentService evaContentServiceImpl;

	@RequestMapping(value = "selYuehuiVo", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查询所有约会")
	public List<YuehuiVo> selYuehuiVo(HttpServletRequest request){
		String yUcount = request.getSession().getAttribute("user")+"";
		return yueHuiServiceImpl.selYuehuiVo(yUcount);
	}
	
	@RequestMapping(value = "selYuehuiVoTerm", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "条件查询所有约会")
	public List<YuehuiVo> selYuehuiVoTerm(String ySex,HttpServletRequest request){
		String yUcount = request.getSession().getAttribute("user")+"";
		return yueHuiServiceImpl.selYuehuiVoTerm(yUcount,ySex);
	}
	
	@RequestMapping(value = "selYueHuiDetails", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查询约会详情")
	public YuehuiDetails selYueHui(int yId) {
		 YuehuiDetails selDetails = yueHuiServiceImpl.selDetails(yId);
		 JSONArray array = JSONArray.parseArray(selDetails.getY_img());
		 selDetails.setArray(array);
		 return selDetails;
	}
	
	@RequestMapping(value = "selYhask", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查询约会人选")
	public List<YuehuiVo> selYhask(int yId){
		return yueHuiServiceImpl.selYhask(yId);
	}

	@RequestMapping(value = "/delYueHui", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除约会信息")
	public int delYueHui(int id) {
		return yueHuiServiceImpl.delYueHui(id);
	}

	@RequestMapping(value = "/showYueHui", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "后台显示约会信息",httpMethod="POST")
	public Msg showYueHui(int pn,MeiyouYuehui meiyouYuehui) {
		List<MeiyouYuehui> list = yueHuiServiceImpl.showYueHui(meiyouYuehui);
		Map<String,Object> map = PagesMap.getpagesYuiHuiMaps(list, pn);
		return Msg.success().add("pageInfo", map);  
	}
	

	@RequestMapping(value = "/selectAllYueHui", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "后台模糊查询约会信息")
	public Msg selectAllYueHui(String yUCount,int pn) {
		System.out.println(yUCount);
		List<MeiyouYuehui> list = yueHuiServiceImpl.selAllYueHui(yUCount);
		Map<String,Object> map = PagesMap.getpagesYuiHuiMaps(list, pn);
		return Msg.success().add("pageInfo", map); 
	}
	
	
	@RequestMapping(value = "/fabuYuehui", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "确认发布约会")
	public Msg Fabu(@RequestParam("mfile") MultipartFile[] mfile,String ySex,String yAddress,String yDate,String yContext,
			Integer yMeijin,String yPingtai,HttpServletRequest request,String pay){
		if(request.getSession().getAttribute("user")==null) {
			System.out.println("session值位空");
			Msg.fail().add("msg","未登陆" );
		}else {
		String uCount=request.getSession().getAttribute("user")+"";
		System.out.println(uCount);
		double meijin = Double.parseDouble(userServiceImpl.selUserByUcount(uCount));
		System.out.println(meijin);
		String num=appsetting.selFaBuJin();
		int fabujin=Integer.parseInt(num);
		System.out.println(fabujin);
		if(meijin>=fabujin+yMeijin){
			String payword = userServiceImpl.selUserPayByUcount(uCount);
			System.out.println(payword);
			if(pay!=null&&pay.equals(payword)){
				//这里mfile可以接受前台的文件，可以是一个，也可以是多个，这正是MultipartFile强大的地方。
				HashMap<String, String> map=new HashMap<String, String>();
				//建一个Map便于返回json
				String filePath =null;
				String fileName[]=new String[mfile.length];
				Date date=new Date();
				//根据传递文件个数返回文件（{msg1:"sss.png",msg2:"aa.jpg"}
				String file = "[";
				if (mfile != null && mfile.length > 0) {
				//判断使用有文件上传
					for (int i = 0; i < mfile.length; i++) {
						//循环上传（多文件上传）
						try {
							Calendar cale = null;	
							cale = Calendar.getInstance();
							int year = cale.get(Calendar.YEAR);
							int month = cale.get(Calendar.MONTH) + 1;
							int day = cale.get(Calendar.DATE);
							String address = Context.fwqaddress;
							//给图片重命名加上日期前缀
							filePath= request.getSession().getServletContext().getRealPath("/") ;
							//获取服务器img文件夹地址（这里指的是local:8080/项目名/img）
							fileName[i]= "/imgs/" + year + ""+ month + "" + day + "_" + mfile[i].getOriginalFilename();
							//重命名图片。
							String type = fileName[i].substring(fileName[i].lastIndexOf(".")+1, fileName[i].length());
							//截取文件后缀判断是否是一张图片
							if((type.equals("png"))||(type.equals("jpg"))||(type.equals("jpeg"))){
								int length = mfile[i].getBytes().length;
								if (!((length / 1000) > 5120)) {
									
									//判断图片地址
									map.put("msg"+i, fileName[i]);
									//将图片输出到制定的文件夹目录中
									mfile[i].transferTo(new File(filePath,fileName[i]));
									if(i==mfile.length-1){
										file +="\""+address+fileName[i]+"\"]";
									}else{
										file +="\""+address+fileName[i]+"\",";
									}
								}else{
									map.put("msg", "图片过大");
								}}else{
								map.put("msg", "只能上传图片啊亲!");}
						} catch (Exception e) {
							e.printStackTrace();
							map.put("msg", "上传失败");}}} else {
					map.put("msg", "请选择文件");}
				MeiyouYuehui meiyouYuehui = new MeiyouYuehui();
				meiyouYuehui.setyTime(date);
				meiyouYuehui.setyState("已发布");
				meiyouYuehui.setyAddress(yAddress);
				meiyouYuehui.setyContext(yContext);
				meiyouYuehui.setyMeijin(yMeijin);
				meiyouYuehui.setyPingtai(yPingtai);
				meiyouYuehui.setySex(ySex);
				meiyouYuehui.setyDate(yDate);
				meiyouYuehui.setyUCount(uCount);
				meiyouYuehui.setyImg(file);
				int index=yueHuiServiceImpl.insYueHui(meiyouYuehui);
				if(index>0){
					MeiyouPtjls meiyouPtjls=new MeiyouPtjls();
					meiyouPtjls.setpMeijin(fabujin);
					meiyouPtjls.setpTime(date);
					meiyouPtjls.setpUCount(uCount);
					int ptjls = ptjlsServiceImpl.insPtjls(meiyouPtjls);
					int upd = 0;
					if(yPingtai.equals("平台担保")){
						int chenyijin = Integer.parseInt(appsetting.selChenYiJin());
						double uMeijin=meijin-(yMeijin+fabujin+chenyijin);
						upd = userServiceImpl.updUserMeijin(uMeijin,uCount);
					}else{
					double uMeijin=meijin-(yMeijin+fabujin);
					upd = userServiceImpl.updUserMeijin(uMeijin,uCount);
					}
					if(ptjls>0 && upd>0){
						return Msg.success();
					}
				}
			}else {
				return Msg.fail();
			}
		}else{
			return Msg.fail();
		}
		}
		return Msg.fail();
		
	}
	@RequestMapping(value = "/YuehuiApply", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "约会报名")
	public Msg YuehuiApply(String uCount,String pay,int yId){
		double meijin = Double.parseDouble(userServiceImpl.selUserByUcount(uCount));
		String payword = userServiceImpl.selUserPayByUcount(uCount);
		if(payword!=null&&!payword.equals("")&&payword.equals(pay)){
			int Apply=1;
			double uMeijin=meijin-Apply;
			int upd = userServiceImpl.updUserMeijin(uMeijin, uCount);
			Date date = new Date();
			MeiyouPtjls meiyouPtjls=new MeiyouPtjls();
			meiyouPtjls.setpMeijin(Apply);
			meiyouPtjls.setpTime(date);
			meiyouPtjls.setpUCount(uCount);
			int ptjls = ptjlsServiceImpl.insPtjls(meiyouPtjls);
			if(ptjls>0&&upd>0){
				MeiyouYhask meiyouYhask = new MeiyouYhask();
				meiyouYhask.setyYId(yId);
				meiyouYhask.setyState("待确定");
				meiyouYhask.setyTime(date);
				meiyouYhask.setyUCount(uCount);
				int index = yueHuiServiceImpl.insYhask(meiyouYhask);
				if(index>0){
				    return Msg.success();
				}else {
					return Msg.fail();
				}
			}
		}
		else{
			return Msg.fail();
		}
		return Msg.fail();
	}
	@RequestMapping(value = "/updYhState", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "确认约会人选")
	public Msg updState(int yId,String xCount,HttpServletRequest request){
		String uCount=request.getSession().getAttribute("user")+"";
		int index = yueHuiServiceImpl.updState(yId);
		if(index>0){
			MeiyouXtinform meiyouXtinform = new MeiyouXtinform();
			Date date = new Date();
			meiyouXtinform.setxCount(xCount);
			meiyouXtinform.setxContent(uCount+"已经确认了您的约会报名，请按时赴约");
			meiyouXtinform.setxTime(date);
			meiyouXtinform.setxUcount(uCount);
			xtinformServiceImpl.insXtinform(meiyouXtinform);
			return Msg.success();
		}
		return Msg.fail();
	}
	
	@RequestMapping(value = "yhPingxing", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "推拿评星")
	public Msg tnPingxing(int yAssess,int yId,String eUBcount,HttpServletRequest request){
		String eUCount = request.getSession().getAttribute("user")+"";
		Date date = new Date();
		MeiyouEvaluate meiyouEvaluate = new MeiyouEvaluate();
		int assess = yueHuiServiceImpl.selYuehuiAssess(yId);
		if(assess==0){
			yueHuiServiceImpl.updYuehuiAssess(yAssess, yId);
			meiyouEvaluate.setContent(Integer.toString(yAssess));
			meiyouEvaluate.seteUBcount(eUBcount);
			meiyouEvaluate.setTime(date);
			meiyouEvaluate.seteUCount(eUCount);
			meiyouEvaluate.setyId(yId);
			evaContentServiceImpl.insEvaluate(meiyouEvaluate);
			return Msg.success();
			
		}else {
			yAssess=(assess+yAssess)/2;
			yueHuiServiceImpl.updYuehuiAssess(yAssess, yId);
			meiyouEvaluate.setContent(Integer.toString(yAssess));
			meiyouEvaluate.seteUBcount(eUBcount);
			meiyouEvaluate.setTime(date);
			meiyouEvaluate.seteUCount(eUCount);
			meiyouEvaluate.setyId(yId);
			evaContentServiceImpl.insEvaluate(meiyouEvaluate);
			return Msg.success();
		}
	}
}
